package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.igas.bomp.facade.BompMchntInspectService;
import cc.rengu.igas.bomp.facade.bean.InspectTaskDetailBean;
import cc.rengu.igas.bomp.facade.request.InspectTaskDetailListQueryRequest;
import cc.rengu.igas.bomp.facade.request.MchntInspectInfoManagerRequest;
import cc.rengu.igas.bomp.facade.request.MchntInspectInfoQueryRequest;
import cc.rengu.igas.bomp.facade.request.MchntInspectListQueryRequest;
import cc.rengu.igas.bomp.facade.response.InspectTaskDetailListQueryResponse;
import cc.rengu.igas.bomp.facade.response.MchntInspectInfoManagerResponse;
import cc.rengu.igas.bomp.facade.response.MchntInspectInfoQueryResponse;
import cc.rengu.igas.bomp.facade.response.MchntInspectListQueryResponse;
import cc.rengu.igas.bomp.facade.result.Result;
import cc.rengu.redp.bizimpl.constant.UpmpConstant;
import cc.rengu.redp.bizimpl.enums.BompTxnNumEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.InspectTaskDetail;
import cc.rengu.redp.bizimpl.upmp.dao.InspectTaskDetailMapper;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpSysParam;
import cc.rengu.redp.bizimpl.upmp.service.IInspectTaskDetailService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 刘玉亮.LL
 */
@Slf4j
@Service
public class InspectTaskDetailServiceImpl extends ServiceImpl<InspectTaskDetailMapper, InspectTaskDetail> implements IInspectTaskDetailService {
    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    /**
     * 商户巡检记录查询 M00BM042
     */
    @Override
    public IPage<InspectTaskDetailBean> findPageFromBomp(HttpServletRequest request, QueryRequest queryRequest, UpmpUserInfoVO user, BompMchntInspectService mchntInspectService, String traceNo) throws RedpException {
       Page<InspectTaskDetailBean> page = new Page<>();
        SortUtil.handlePageSort(queryRequest, page, true);
       String instId = request.getParameter("instId");
        if (Common.isBlank(instId)) {
            if (Common.isNotBlank(user) && Common.isNotBlank(user.getInstId())) {
                instId = user.getInstId();
            }
        } else {
            //非运营中心管理员使用与自己所属法人行不符的法人行号查询数据时提示异常
            if (Common.isNotBlank(user) && Common.isNotBlank(user.getInstId())
                    && !user.isAdmin() && !instId.equals(user.getInstId())) {
                log.error("商户巡检记录查询请求参数与用户身份不符");
                throw new RedpException("商户巡检记录查询请求参数与用户身份不符");
            }
        }
        String mchntNo = request.getParameter("mchntNo");
        String mchntName = request.getParameter("mchntName");
        String signInstId = request.getParameter("signInstId");
        String inspectInstId = request.getParameter("inspectInstId");
        String mchntType = request.getParameter("mchntType");
        String inspectType = request.getParameter("inspectType");
        String inspectBeginTime = request.getParameter("inspectBeginTime");
        String inspectEndTime = request.getParameter("inspectEndTime");
        String inspectStatus = request.getParameter("inspectStatus");

        try {
            MchntInspectListQueryRequest req = new MchntInspectListQueryRequest();
            req.setUserId(user.getId());
            req.setMchntNo(mchntNo);
            req.setMchntName(mchntName);
            req.setMchntType(mchntType);
            req.setSignInstId(signInstId);
            req.setInspectInstId(inspectInstId);
            req.setInspectType(inspectType);
            req.setStartDate(inspectBeginTime);
            req.setEndDate(inspectEndTime);
            req.setInspectStatus(inspectStatus);
            req.setInstId(instId);
            req.setPageSize(queryRequest.getPageSize());
            req.setPageIndex(queryRequest.getPageNum());
            req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.mchntInspectListQuery.getType(), instId,null));

            log.info(BompTxnNumEnum.mchntInspectListQuery.getDesc() + "交易请求报文：" + JSON.toJSONString(req));
            Result<MchntInspectListQueryResponse> response = mchntInspectService.mchntInspectListQuery(req);
            log.info(BompTxnNumEnum.mchntInspectListQuery.getDesc() + "交易返回报文：" + JSON.toJSONString(response));
            List<InspectTaskDetailBean> list = Lists.newArrayList();
            if (response.isSuccess()) {
                MchntInspectListQueryResponse resp = response.getResult();
                log.info(BompTxnNumEnum.mchntInspectListQuery.getDesc() + "交易成功");
                if (Common.isNotBlank(resp) && CollectionUtils.isNotEmpty(resp.getInspectTaskDetailList())) {
                    list = resp.getInspectTaskDetailList();
                    UpmpSysParam defaultInst = upmpSysParamService.getById(UpmpConstant.DEAFULT_INST_PARAM_ID);
                    UpmpSysParam dataDict = upmpSysParamService.findByPrimaryKey(instId, defaultInst.getPrimaryValue(),"599");
                    for(InspectTaskDetailBean inspectTaskDetailBean:list){
                        inspectTaskDetailBean.setInstName(dataDict.getPrimaryValue());
                    }
                    page.setRecords(list);
                    page.setTotal(resp.getTotalRows());
                } else {
                    page.setRecords(list);
                    page.setTotal(0);
                }
                return page;
            } else {
                page.setRecords(list);
                page.setTotal(0);
                return page;
            }
        } catch (Exception e) {
            log.error("商户巡检记录查询出现异常", e);
            throw new RedpException("商户巡检记录查询出现异常:" + e.getMessage());
        }
    }

    /**
     * 商户巡检信息详情查询 M00BM040
     */
    @Override
    public MchntInspectInfoQueryResponse mchntInspectInfoQuery(HttpServletRequest request, UpmpUserInfoVO user, BompMchntInspectService mchntInspectService, String traceNo) throws RedpException {
        String instId = request.getParameter("instId");
        if (Common.isBlank(instId)) {
            if (Common.isNotBlank(user) && Common.isNotBlank(user.getInstId())) {
                instId = user.getInstId();
            }
        } else {
            // 非运营中心管理员使用与自己所属法人行不符的法人行号查询数据时提示异常
            if (Common.isNotBlank(user) && Common.isNotBlank(user.getInstId())
                    && !user.isAdmin() && !instId.equals(user.getInstId())) {
                log.error("商户巡检信息详情查询请求参数与用户身份不符");
                throw new RedpException("商户巡检信息详情查询请求参数与用户身份不符");
            }
        }

        String inspectTaskNo = request.getParameter("inspectTaskNo");
        String mchntNo = request.getParameter("mchntNo");

        try {
            MchntInspectInfoQueryRequest req = new MchntInspectInfoQueryRequest();
            req.setUserId(user.getId());
            req.setInspectTaskNo(inspectTaskNo);
            req.setMchntNo(mchntNo);
            req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.mchntInspectInfoQuery.getType(), instId,null));

            log.info(BompTxnNumEnum.mchntInspectInfoQuery.getDesc() + "交易请求报文：" + JSON.toJSONString(req));
            Result<MchntInspectInfoQueryResponse> response = mchntInspectService.mchntInspectInfoQuery(req);
            log.info(BompTxnNumEnum.mchntInspectInfoQuery.getDesc() + "交易返回报文：" + JSON.toJSONString(response));

            if (response.isSuccess()) {
                MchntInspectInfoQueryResponse resp = response.getResult();
                log.info(BompTxnNumEnum.mchntInspectInfoQuery.getDesc() + "交易成功");
                return resp;
            } else {
                log.info(BompTxnNumEnum.mchntInspectInfoQuery.getDesc() + "交易没有获得返回信息");
                return null;
            }
        } catch (Exception e) {
            log.error("商户巡检信息详情查询出现异常", e);
            throw new RedpException("商户巡检信息详情查询出现异常:" + e.getMessage());
        }
    }

    /**
     * 商户巡检信息管理 M00BM041
     */
    @Override
    public OperationResult mchntInspectInfoManager(MchntInspectInfoManagerRequest req, BompMchntInspectService mchntInspectService) {
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();

        log.info(BompTxnNumEnum.mchntInspectInfoManager.getDesc() + "交易请求报文：" + JSON.toJSONString(req));
        Result<MchntInspectInfoManagerResponse> resp = mchntInspectService.mchntInspectInfoManager(req);
        log.info(BompTxnNumEnum.mchntInspectInfoManager.getDesc() + "交易应答报文：" + JSON.toJSONString(resp));
        if (resp.isSuccess()) {
            MchntInspectInfoManagerResponse response = resp.getResult();
            //
            if (BusinessContainer.BSPS_SUCCESS.equals(response.getRespCode())) {
                result.put("respCode", response.getRespCode());
                result.put("respMsg", response.getRespDesc());

                log.error(BompTxnNumEnum.mchntInspectInfoManager.getDesc() + "交易成功");
                return OperationResult.buildSuccessResult(BompTxnNumEnum.mchntInspectInfoManager.getDesc() + "交易成功", result);
            } else {
                result.put("respCode", response.getRespCode());
                result.put("respMsg", response.getRespDesc());
                return OperationResult.buildFailureResult(BompTxnNumEnum.mchntInspectInfoManager.getDesc() + "交易失败", result);
            }
        } else {
            result.put("resCode", BusinessContainer.ERROR);
            result.put("resMsg", BompTxnNumEnum.mchntInspectInfoManager.getDesc() + "没有获得返回报文");
            log.error(BompTxnNumEnum.mchntInspectInfoManager.getDesc() + "交易没有获得返回信息");
            return OperationResult.buildFailureResult(BompTxnNumEnum.mchntInspectInfoManager.getDesc() + "交易失败", result);
        }
    }
    @Override
    public IPage<InspectTaskDetailBean> findPageBompList(HttpServletRequest request, QueryRequest queryRequest, UpmpUserInfoVO user, BompMchntInspectService mchntInspectService, String traceNo) throws RedpException {
        Page<InspectTaskDetailBean> page = new Page<>();
        SortUtil.handlePageSort(queryRequest, page, true);

        String instId = request.getParameter("instId");
        String inspectTaskNo = request.getParameter("inspectTaskNo");
        String mchntNo = request.getParameter("mchntNo");
        String mchntName = request.getParameter("mchntName");
        String signInstId = request.getParameter("signInstId");
        String inspectInstId = request.getParameter("inspectInstId");
        String inspectStatus = request.getParameter("inspectStatus");
        String mchntType = request.getParameter("mchntType");
        String mchntLevel = request.getParameter("mchntLevel");
        String managerId = request.getParameter("managerId");
        if (Common.isBlank(instId)) {
            if (Common.isNotBlank(user) && Common.isNotBlank(user.getInstId())) {
                instId = user.getInstId();
            }
        }else {
            //非运营中心管理员使用与自己所属法人行不符的法人行号查询数据时提示异常
            if (Common.isNotBlank(user) && Common.isNotBlank(user.getInstId())
                    && !user.isAdmin()&&!instId.equals(user.getInstId())) {
                log.error("巡检任务详情列表查询请求参数与用户身份不符");
                throw new RedpException("商户巡检记录查询请求参数与用户身份不符");
            }
        }
        if(Common.isBlank(inspectTaskNo)) {
            log.info("巡检任务详情列表查询[inspectTaskNo]为空，无法检索数据");
            throw new RedpException("巡检任务详情列表查询[inspectTaskNo]为空，无法检索数据");
        }

        InspectTaskDetailListQueryRequest req=new InspectTaskDetailListQueryRequest();
        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.inspectTaskDetailListQuery.getType(),instId,null));
        req.setInspectTaskNo(inspectTaskNo);
        req.setPageSize(queryRequest.getPageSize());
        req.setPageIndex(queryRequest.getPageNum());
        req.setUserId(user.getId());
        req.setMchntNo(mchntNo);
        req.setMchntName(mchntName);
        req.setSignInstId(signInstId);
        req.setInspectInstId(inspectInstId);
        req.setInspectStatus(inspectStatus);
        req.setMchntType(mchntType);
        req.setMchntLevel(mchntLevel);
        req.setManagerId(managerId);

        try{
            log.info("巡检任务详情列表查询"+BompTxnNumEnum.inspectTaskDetailListQuery.getDesc()+"交易请求报文：" + JSON.toJSONString(req));
            Result<InspectTaskDetailListQueryResponse> response = mchntInspectService.inspectTaskDetailListQuery(req);
            log.info("巡检任务详情列表查询"+BompTxnNumEnum.inspectTaskDetailListQuery.getDesc()+"交易返回报文：" + JSON.toJSONString(response));
            List<InspectTaskDetailBean> list = Lists.newArrayList();
            if(response.isSuccess()){
                InspectTaskDetailListQueryResponse resp = response.getResult();
                if (BusinessContainer.BSPS_SUCCESS.equals(resp.getRespCode())) {
                    log.info("巡检任务详情列表查询"+BompTxnNumEnum.inspectTaskDetailListQuery.getDesc()+"交易成功");
                    if(Common.isNotBlank(resp)&& CollectionUtils.isNotEmpty(resp.getInspectTaskDetailList())){
                        list = resp.getInspectTaskDetailList();
                        String optFlag = request.getParameter("optFlag");
                        if("expor".equals(optFlag)){
                            for(InspectTaskDetailBean inspectTaskDetailBean : list){
                                String inspectTaskType = inspectTaskDetailBean.getInspectTaskType();
                                if("01".equals(inspectTaskType)){
                                    inspectTaskType = "正常商户巡检";
                                }else if("02".equals(inspectTaskType)){
                                    inspectTaskType = "抽检商户巡检";
                                }else if("03".equals(inspectTaskType)){
                                    inspectTaskType = "交易量偏低商户巡检";
                                }else if("04".equals(inspectTaskType)){
                                    inspectTaskType = "风险商户巡检";
                                }else if("05".equals(inspectTaskType)){
                                    inspectTaskType = "新入驻商户巡检";
                                }
                                inspectTaskDetailBean.setInspectTaskType(inspectTaskType);
                                String mchntTp = inspectTaskDetailBean.getMchntType();
                                if("00".equals(mchntTp)){
                                    mchntTp = "普通商户";
                                }else if("10".equals(mchntTp)){
                                    mchntTp = "连锁商户";
                                }else if("11".equals(mchntTp)){
                                    mchntTp = "连锁商户门店";
                                }else if("20".equals(mchntTp)){
                                    mchntTp = "小微商户";
                                }
                                inspectTaskDetailBean.setMchntType(mchntTp);
                                String inspectType = inspectTaskDetailBean.getInspectType();
                                if("00".equals(inspectType)){
                                    inspectType = "电话巡检";
                                }else if("10".equals(inspectType)){
                                    inspectType = "商户自助巡检";
                                }else if("20".equals(inspectType)){
                                    inspectType = "线下现场巡检";
                                }
                                inspectTaskDetailBean.setInspectType(inspectType);
                                String inspectSta = inspectTaskDetailBean.getInspectStatus();
                                if("00".equals(inspectSta)){
                                    inspectSta = "未巡检";
                                }else if("01".equals(inspectSta)){
                                    inspectSta = "巡检待提交";
                                }else if("02".equals(inspectSta)){
                                    inspectSta = "巡检待审核";
                                }else if("03".equals(inspectSta)){
                                    inspectSta = "巡检拒绝";
                                }else if("10".equals(inspectSta)){
                                    inspectSta = "已巡检";
                                }
                                inspectTaskDetailBean.setInspectStatus(inspectSta);
                            }
                        }
                        page.setRecords(list);
                        page.setTotal(resp.getTotalRows());
                    }else{
                    page.setRecords(list);
                    page.setTotal(0);
                    }
                    return page;
                }else {
                    log.error("巡检任务详情列表查询"+ BompTxnNumEnum.inspectTaskDetailListQuery.getDesc()+"交易失败");
                    page.setRecords(list);
                    page.setTotal(0);
                }

            }else{
                log.error("巡检任务详情列表查询"+BompTxnNumEnum.inspectTaskDetailListQuery.getDesc()+"交易没有获得返回信息");
                page.setRecords(list);
                page.setTotal(0);
            }
        }catch (Exception e){
            log.error("巡检任务详情列表查询"+BompTxnNumEnum.inspectTaskDetailListQuery.getDesc()+"交易出现异常，异常信息："+e.getMessage(),e);
            throw new RedpException("巡检任务详情列表查询"+BompTxnNumEnum.inspectTaskDetailListQuery.getDesc()+"交易出现异常，异常信息："+e.getMessage());
        }
        return page;
    }
}
